package fautil

import (
	"archive/zip"
	"bufio"
	"bytes"
	"gitee.com/bupt-zkjc/fabric2.2-interface/common/log"
	"gitee.com/bupt-zkjc/fabric2.2-interface/config_yaml"

	"fmt"
	//"gitee.com/bupt-zkjc/fabric2.2-interface/config"
	"gitee.com/bupt-zkjc/fabric2.2-interface/constant"
	"gitee.com/bupt-zkjc/fabric2.2-interface/model"
	"io"
	"os"
	"os/exec"
	"path/filepath"
)
var logger = log.GetLogger("fabric.util", log.INFO)


func GetChannelTx(f model.FabricChain) string {
	return filepath.Join(f.ChannelPath, f.ChannelName+constant.Tx)
}

func Exec_shell(command string, channelPath string) error{
	cmd := exec.Command("/bin/bash", "-c", command)
	cmd.Dir = channelPath
	var out bytes.Buffer

	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		logger.Error(err)
		return err
	}
	logger.Info(out.String())
	return nil
}
func checkFileIsExist(filename string) bool {
	var exist = true
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

func WriteFile(args string) error{
	//filePath := config.Config.GetString("InterfaceRootPath") + "config_yaml/chainArgs.txt"
	path, err := config_yaml.GetParentDirectory()
	if err != nil {
		return  err
	}
	filePath := filepath.Join(path, constant.Dirpath, "chainArgs.txt")
	file, err := os.OpenFile(filePath, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0666)
	if err != nil {
		logger.Error("open file error=%v\n", err)
		return err
	}
	defer file.Close()
	/*
	name := "chain1\n"
	orgName := "firstOrg\n"
	orderersUrl := "grpcs://localhost:7050 grpcs://localhost:8050 grpcs://localhost:9050\n"
	peersUrl := "grpcs://localhost:7051 grpcs://localhost:8051\n"
	cryptoPath := "/home/mjl/blockchain-application-using-fabric-java-sdk/network/crypto-config\n"
*/
	writer := bufio.NewWriter(file)
	writer.WriteString(args)

	writer.Flush()
	return nil
}

func DeCompress(zipFile, dest string) error {
	zipReader, err := zip.OpenReader(zipFile)
	if err != nil {
		return err
	}

	defer zipReader.Close()
	for _, file := range zipReader.Reader.File {
		zippedFile, err := file.Open()
		if err != nil {
			logger.Info("Open error: ", err)
			return err
		}
		defer zippedFile.Close()

		extractedFilePath := filepath.Join(dest, file.Name)
		if file.FileInfo().IsDir() {
			logger.Info("正在创建目录: ", extractedFilePath)
			os.MkdirAll(extractedFilePath, file.Mode())
		} else {
			// 如果文件在目录中间，那么file.Name也会包含目录的
			logger.Info("正在提取文件: ", file.Name)
			outputFile, err := os.OpenFile(extractedFilePath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0777)
			if err != nil {
				fmt.Println(err)
				return err
			}
			defer outputFile.Close()

			_, err = io.Copy(outputFile, zippedFile)
			if err != nil {
				logger.Info("Err: ", err)
				return err
			}
		}
	}
	return nil
}